<?php

namespace wap\controllers;

use libs\Grab;
use Yii;
use yii\helpers\Html;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use yii\helpers\Url;

/**
 * Ajax Controller
 */
class AjaxController extends \yii\web\Controller
{
    public $enableCsrfValidation = false;

    private $return = [
        'error' => 1,
        'msg' => '系统错误！',
    ];

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'post' => ['select'],
                ],
            ],
        ];
    }

    /**
     * 级联下拉表单
     *
     * @param $model
     * @param $input
     *
     * @return string
     */
    public function actionSelect($model, $input)
    {
        $select = '';
        $parent_id = Yii::$app->request->post('parent_id');

        if($parent_id){
            $datas = $model::getSelectData($parent_id);
            if($datas){
                $params = [
                    'class' => 'form-control form-control-inline',
                    'ajax-select' => Url::to(['ajax/select', 'model' => $model, 'input' => $input]),
                ];

                if(!$parent_id){
                    $params['prompt'] = '请选择';
                }

                $select = Html::dropDownList($input, '', $datas, $params);
            }
        }

        return $this->success(['html' => $select]);
    }

    public function actionOptions($model, $field)
    {
        $value = Yii::$app->request->post('value');

        return $this->success(['html' => $model::getOptions([$field => $value])]);
    }

    private function error($params)
    {
        $return = array_merge($this->return, $params);
        $return['error'] = 1;
        return Json::encode($return);
    }

    private function success($params)
    {
        $return = array_merge($this->return, $params);
        $return['error'] = 0;
        return Json::encode($return);
    }
}
